package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("spit")
public class SpitController {
    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.查所有
    @GetMapping()
    public Result findAll(){
        List<Spit> spitList= spitService.findAll();
        return new Result(true, StatusCode.OK,"查所有成功",spitList);
    }
    //2.查单个
    @GetMapping("{spitId}")
    public Result findById(@PathVariable String spitId){
        Spit spit=spitService.findById(spitId);
        return new Result(true,StatusCode.OK,"查单个成功",spit);
    }
    //3.增加
    @PostMapping()
    public Result add(@RequestBody Spit spit){
        spitService.add(spit);
        return new Result(true,StatusCode.OK,"增加成功");
    }
    //4.修改
    @PutMapping("{spitId}")
    public Result update(@RequestBody Spit spit,@PathVariable String spitId){
        spit.set_id(spitId);
        spitService.update(spit);
        return new Result(true,StatusCode.OK,"修改成功");
    }
    //5.删除
    @DeleteMapping("{spitId}")
    public Result delete(@PathVariable String spitId){
        spitService.deleteById(spitId);
        return new Result(true,StatusCode.OK,"删除成功");
    }
    //6.根据parentId查询
    @GetMapping("comment/{parentid}/{page}/{size}")
    public Result findByParentId(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
        PageResult pageResult= spitService.findByParentId(parentid,page,size);
        return new Result(true,StatusCode.OK,"查询parentId成功",pageResult);
    }
    //7.吐槽点赞
    @PutMapping("thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        String s = (String) redisTemplate.opsForValue().get("thumbup_"+ spitId);
        if (s==null){
            spitService.thumbup(spitId);
            redisTemplate.opsForValue().set("thumbup_"+spitId,"test");
            return new Result(true,StatusCode.OK,"点赞成功");
        }else {
            return new Result(false,StatusCode.REPERROR,"点赞失败,不能重复点赞");
        }
    }
}
